package com.favccxx.message.infrastructure.util.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

@Slf4j
public class JacksonUtil {

    private static ObjectMapper objectMapper = new ObjectMapper();

    public JacksonUtil() {
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
        this.objectMapper = new ObjectMapper().findAndRegisterModules();
    }

    public JacksonUtil(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }


    public static String toJsonString(Object obj) {
        String jsonStr = null;
        try {
            jsonStr = objectMapper.writeValueAsString(obj);
            return jsonStr;
        } catch (JsonProcessingException e) {
            log.error(" Format json error, " + e.getMessage());
        }
        return "";

    }

    public static <T> T jsonToObject(String jsonStr, Class<T> classInfo) throws IOException {
        T obj = null;
        obj = objectMapper.readValue(jsonStr, classInfo);
        return obj;
    }

}
